package cn.shuibo.advice;

import cn.shuibo.util.Base64Util;
import cn.shuibo.util.RSAUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;

/**
 * 加密工具
 * Author:Bobby
 * DateTime:2019/4/9
 **/
public class DecryptHttpInputMessage implements HttpInputMessage{

    private Logger log = LoggerFactory.getLogger(this.getClass());
    private HttpHeaders headers;
    private InputStream body;


    /**
     * 验签
     * @param inputMessage
     * @param privateKey
     * @param charset
     * @param showLog
     * @throws Exception
     */
    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog) throws Exception {

        log.info("请求参数解密-----打印日志------{}",privateKey);
        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        }

        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
                .lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody;
        //未加密的不进行解密
        if (content.startsWith("{")) {
            log.info("DecryptHttpInputMessage--Unencrypted without decryption:{}", content);
            decryptBody = content;
        } else {
            StringBuilder json = new StringBuilder();
            content = content.replaceAll(" ", "+");

            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split("\\|");
                for (String value : contents) {
                    value = new String(RSAUtil.decrypt(Base64Util.decode(value), privateKey), charset);
                    json.append(value);
                }
            }
            decryptBody = json.toString();
            if(showLog) {
                log.info("Encrypted data received：{},After decryption：{}", content, decryptBody);
            }
        }

        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody(){
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }


    /**
     * 解密消息体
     *
     * @param inputMessage 消息体
     * @return 明文
     */
//     private String decryptBody(HttpInputMessage inputMessage) throws IOException {
//         InputStream encryptStream = inputMessage.getBody();
//         String requestBody = StreamUtils.copyToString(encryptStream, Charset.defaultCharset());
//         // 验签过程
//         HttpHeaders headers = inputMessage.getHeaders();
//         if (CollectionUtils.isEmpty(headers.get("clientType"))
//                 || CollectionUtils.isEmpty(headers.get("timestamp"))
//                 || CollectionUtils.isEmpty(headers.get("salt"))
//                 || CollectionUtils.isEmpty(headers.get("signature"))) {
//             throw new ResultException(SECRET_API_ERROR, "请求解密参数错误，clientType、timestamp、salt、signature等参数传递是否正确传递");
//         }
//
//         String timestamp = String.valueOf(Objects.requireNonNull(headers.get("timestamp")).get(0));
//         String salt = String.valueOf(Objects.requireNonNull(headers.get("salt")).get(0));
//         String signature = String.valueOf(Objects.requireNonNull(headers.get("signature")).get(0));
//         String privateKey = SecretFilter.clientPrivateKeyThreadLocal.get();
//         ReqSecret reqSecret = JSON.parseObject(requestBody, ReqSecret.class);
//         String data = reqSecret.getData();
//         String newSignature = "";
//         if (!StringUtils.isEmpty(privateKey)) {
//             newSignature = Md5Utils.genSignature(timestamp + salt + data + privateKey);
//         }
//         if (!newSignature.equals(signature)) {
//             // 验签失败
//             throw new ResultException(SECRET_API_ERROR, "验签失败，请确认加密方式是否正确");
//         }
//
//         try {
//             String decrypt = EncryptUtils.aesDecrypt(data, privateKey);
//             if (StringUtils.isEmpty(decrypt)) {
//                 decrypt = "{}";
//             }
//             return decrypt;
//         } catch (Exception e) {
//             log.error("error: ", e);
//         }
//         throw new ResultException(SECRET_API_ERROR, "解密失败");
//     }
// }
}
